"""
日志配置模块
为Dolphin API提供统一的日志配置
"""

import logging
import logging.handlers
import os
import sys
from datetime import datetime
from pathlib import Path


def setup_logging(
    log_level: str = "INFO",
    log_dir: str = "logs",
    max_file_size: int = 10 * 1024 * 1024,  # 10MB
    backup_count: int = 5,
    enable_console: bool = True,
    enable_file: bool = True
):
    """
    设置日志配置
    
    Args:
        log_level: 日志级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL)
        log_dir: 日志文件目录
        max_file_size: 单个日志文件最大大小（字节）
        backup_count: 保留的日志文件数量
        enable_console: 是否启用控制台输出
        enable_file: 是否启用文件输出
    """
    
    # 创建日志目录
    if enable_file:
        Path(log_dir).mkdir(exist_ok=True)
    
    # 设置日志级别
    numeric_level = getattr(logging, log_level.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError(f'Invalid log level: {log_level}')
    
    # 获取根日志器
    root_logger = logging.getLogger()
    root_logger.setLevel(numeric_level)
    
    # 清除现有的处理器
    for handler in root_logger.handlers[:]:
        root_logger.removeHandler(handler)
    
    # 创建格式器
    detailed_formatter = logging.Formatter(
        fmt='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    simple_formatter = logging.Formatter(
        fmt='%(asctime)s - %(levelname)s - %(message)s',
        datefmt='%H:%M:%S'
    )
    
    # 控制台处理器
    if enable_console:
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setLevel(numeric_level)
        console_handler.setFormatter(simple_formatter)
        root_logger.addHandler(console_handler)
    
    # 文件处理器
    if enable_file:
        # 主日志文件
        log_file = os.path.join(log_dir, 'dolphin_api.log')
        file_handler = logging.handlers.RotatingFileHandler(
            log_file,
            maxBytes=max_file_size,
            backupCount=backup_count,
            encoding='utf-8'
        )
        file_handler.setLevel(numeric_level)
        file_handler.setFormatter(detailed_formatter)
        root_logger.addHandler(file_handler)
        
        # 错误日志文件
        error_log_file = os.path.join(log_dir, 'dolphin_errors.log')
        error_handler = logging.handlers.RotatingFileHandler(
            error_log_file,
            maxBytes=max_file_size,
            backupCount=backup_count,
            encoding='utf-8'
        )
        error_handler.setLevel(logging.ERROR)
        error_handler.setFormatter(detailed_formatter)
        root_logger.addHandler(error_handler)
    
    # 记录日志系统启动信息
    logging.info(f"日志系统已启动 - 级别: {log_level}")
    if enable_file:
        logging.info(f"日志文件目录: {os.path.abspath(log_dir)}")


def get_logger(name: str) -> logging.Logger:
    """
    获取指定名称的日志器
    
    Args:
        name: 日志器名称，通常使用 __name__
        
    Returns:
        配置好的日志器实例
    """
    return logging.getLogger(name)


class APILoggerMixin:
    """
    API日志混入类，为API端点提供统一的日志记录功能
    """
    
    def __init__(self):
        self.logger = get_logger(self.__class__.__name__)
    
    def log_request_start(self, endpoint: str, **kwargs):
        """记录请求开始"""
        details = ", ".join(f"{k}={v}" for k, v in kwargs.items())
        self.logger.info(f"开始处理请求 - 端点: {endpoint}, 参数: {details}")
    
    def log_request_success(self, endpoint: str, duration: float, **kwargs):
        """记录请求成功"""
        details = ", ".join(f"{k}={v}" for k, v in kwargs.items())
        self.logger.info(f"请求处理成功 - 端点: {endpoint}, 耗时: {duration:.2f}s, {details}")
    
    def log_request_error(self, endpoint: str, error: Exception, duration: float = None):
        """记录请求错误"""
        duration_str = f", 耗时: {duration:.2f}s" if duration else ""
        self.logger.error(f"请求处理失败 - 端点: {endpoint}{duration_str}, 错误: {str(error)}", exc_info=True)
    
    def log_model_operation(self, operation: str, **kwargs):
        """记录模型操作"""
        details = ", ".join(f"{k}={v}" for k, v in kwargs.items())
        self.logger.debug(f"模型操作 - {operation}, {details}")


# 预定义的日志配置模板
DEVELOPMENT_CONFIG = {
    "log_level": "DEBUG",
    "enable_console": True,
    "enable_file": True,
    "log_dir": "logs"
}

PRODUCTION_CONFIG = {
    "log_level": "INFO",
    "enable_console": False,
    "enable_file": True,
    "log_dir": "/var/log/dolphin-api",
    "max_file_size": 50 * 1024 * 1024,  # 50MB
    "backup_count": 10
}

TESTING_CONFIG = {
    "log_level": "WARNING",
    "enable_console": True,
    "enable_file": False
}


def setup_development_logging():
    """设置开发环境日志"""
    setup_logging(**DEVELOPMENT_CONFIG)


def setup_production_logging():
    """设置生产环境日志"""
    setup_logging(**PRODUCTION_CONFIG)


def setup_testing_logging():
    """设置测试环境日志"""
    setup_logging(**TESTING_CONFIG)


# 为第三方库设置日志级别
def configure_third_party_loggers():
    """配置第三方库的日志级别"""
    # 设置常见第三方库的日志级别
    third_party_loggers = {
        'transformers': logging.WARNING,
        'torch': logging.WARNING,
        'PIL': logging.WARNING,
        'uvicorn': logging.INFO,
        'fastapi': logging.INFO,
        'httpx': logging.WARNING,
        'urllib3': logging.WARNING,
    }
    
    for logger_name, level in third_party_loggers.items():
        logger = logging.getLogger(logger_name)
        logger.setLevel(level)


if __name__ == "__main__":
    # 测试日志配置
    setup_development_logging()
    configure_third_party_loggers()
    
    logger = get_logger(__name__)
    
    logger.debug("这是一条调试信息")
    logger.info("这是一条信息")
    logger.warning("这是一条警告")
    logger.error("这是一条错误信息")
    
    print("日志配置测试完成，请检查控制台输出和logs目录中的文件")